﻿using System;
using System.Linq;
using System.Reflection;

namespace AwesomeChromeFormUI.Reflections
{
    public class AttributeUtil
    {
        /// <summary>
        /// 找到第一个带注解的类
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static Type FindFirstAnnotatedClass<T>() where T : Attribute
        {
            return AppDomain.CurrentDomain.GetAssemblies()
               .SelectMany(a => a.GetTypes())
               .Where(t => t.IsClass && t.GetCustomAttribute<T>() != null)
               .FirstOrDefault();
        }

        /// <summary>
        /// 找到第一个带注解的类
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="S">继承自S类</typeparam>
        /// <returns></returns>
        public static Type FindFirstAnnotatedClass<T,S>() where T : Attribute
        {
            return AppDomain.CurrentDomain.GetAssemblies()
               .SelectMany(a => a.GetTypes())
               .Where(t => t.IsClass && t.GetCustomAttribute<T>() != null && typeof(S).IsAssignableFrom(t))
               .FirstOrDefault();
        }
    }
}
